import requests
from bs4 import BeautifulSoup
import csv

def getHTMLText(url):
    try:
        r = requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding = 'utf-8'
        return r.text
    except:
        return "获取文本异常"

def fillUnivList(ulist,soup):
    data = soup.find('div', attrs='right-1').find_all('li')
    for lis in data:
        month = lis.find('em').text.strip()
        day = lis.find('i').text.strip()
        title = lis.find('h3').text.strip()
        context = lis.find('p').text.strip()
        date = month + day + "日"
        ulist.append([date,title,context])

def printUnivList(ulist):
    print(ulist)


def writedatatocsv(ulist):
    with open('data.csv', 'w', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(["日期","标题","内容"])
        num = len(ulist)
        for i in range(num):
            u = ulist[i]
            writer.writerow([u[0],u[1],u[2]])



def main():
    url = 'https://www.zjitc.net/xwzx/xxxw.htm'
    ulist = []  # 存储全部表格数据，二维列表
    html = getHTMLText(url)
    soup = BeautifulSoup(html,"html.parser")
    fillUnivList(ulist,soup)
    writedatatocsv(ulist)
    printUnivList(ulist)
main()